package admin

import (
	"booking/common/handler"
	"booking/common/utils"
	"booking/common/validator"
	"booking/models"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/spf13/cast"
	"github.com/spf13/viper"
)

func Login(c *gin.Context) {
	var loginRequest struct {
		Username string `json:"username" binding:"required" display:"用户名"`
		Password string `json:"password" binding:"required" display:"密码"`
	}
	if err := c.ShouldBindJSON(&loginRequest); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}
	var admin models.Admin
	models.Db.Model(models.Admin{}).
		Where(map[string]any{
			"username": loginRequest.Username,
			"status":   models.StatusEnabled,
		}).
		First(&admin)
	if admin.Id == 0 || !utils.BcryptCheck(loginRequest.Password, admin.Password) {
		handler.Error("账号密码错误", c)
		return
	}
	// 生成 JWT 令牌
	token, err := generateToken(admin)
	if err != nil {
		handler.Error(err.Error(), c)
		return
	}

	handler.Success(map[string]any{
		"nickname":      admin.Nickname,
		"username":      admin.Username,
		"mobile":        admin.Mobile,
		"authorization": token,
	}, c)
}
func generateToken(admin models.Admin) (string, error) {
	jwtSecret := []byte(viper.GetString("jwt.secret"))
	token := jwt.New(jwt.SigningMethodHS256)
	claims := token.Claims.(jwt.MapClaims)
	claims["id"] = cast.ToInt(admin.Id)
	claims["username"] = admin.Username
	claims["nickname"] = admin.Nickname
	claims["mobile"] = admin.Mobile
	second := int64(viper.GetInt("jwt.expire"))
	claims["expires"] = time.Now().Add(time.Second * time.Duration(second)).Unix()
	// 生成签名字符串
	tokenString, err := token.SignedString(jwtSecret)
	if err != nil {
		return "", err
	}

	return "Bearer " + tokenString, nil
}
